import React, { useEffect, useState, useRef } from "react";

import RequestInstance from "@/plugin/requestList";

import { io, Socket, Manager } from "socket.io-client";

export default () => {
  // 请求队列中转站，直接传入react state到RequestInstance对象的回调方法中由于闭包的原因不能获取到最新的state
  const arr = useRef<RequestInstance[]>([]);

  const [list, setList] = useState<RequestInstance[]>([]);

  const init = useRef<boolean>(true);

  const [socketIO, setSocketIO] = useState<Socket>();

  const handleSocket = () => {
    // socket封装
    console.log("socket");
    setSocketIO(io("http://localhost:1818", { autoConnect: true }));
  };

  useEffect(() => {
    if (socketIO) {
      socketIO.on("connect", () => {
        // 客户端只有connect事件没有connection事件，服务端connection和connect都行
        console.log("connection");
        socketIO.emit("my other event", { my: "data" });
      });
      socketIO.on("news", function (data) {
        console.log(data);
      });
    }
  }, [socketIO]);

  useEffect(() => {
    arr.current = [1, 2, 3, 4].map((item, index) => {
      let requestItem = new RequestInstance({
        process: (e: RequestInstance) =>
          setList(arr.current.map((item, n) => (n === index ? e : item))),
        uploadProcess: (e: RequestInstance) =>
          setList(arr.current.map((item, n) => (n === index ? e : item))),
        error: (e: RequestInstance) =>
          setList(arr.current.map((item, n) => (n === index ? e : item))),
        ok: (e: RequestInstance) =>
          setList(arr.current.map((item, n) => (n === index ? e : item))),
        cancel: (e: RequestInstance) =>
          setList(arr.current.map((item, n) => (n === index ? e : item))),
        handleReSend: (e: RequestInstance) =>
          setList(arr.current.map((item, n) => (n === index ? e : item))),
      });
      return requestItem;
    });
    setList(arr.current);
    // 正常的http请求
    let a = new RequestInstance({});
    a.fetch({ method: "GET", url: "http://localhost:1818" }).then((res) =>
      console.log(res)
    );
    handleSocket();
  }, []);

  useEffect(() => {
    if (!init.current || arr.current.length <= 0) return;
    init.current = false;
    // 上传队列实时更新上传状态
    arr.current.forEach((item) => {
      let formData = new FormData();
      formData.append("item", "34234234234234");
      item.upload({ url: "http://localhost:1818", file: formData });
    });
  }, [list]);

  return (
    <div>
      socket and request
      <div>
        {list.map((item, index) => (
          <div key={index}>
            {item.size}: {item.state}
            <button onClick={() => item.reSend()}>重发</button>
          </div>
        ))}
      </div>
    </div>
  );
};
